<template>
  <div class="container">
    <el-card>
      <!-- 顶部输入框和按钮 -->
      <el-row type="flex" justify="space-between" align="middle">
        <el-col :span="12">
          <el-row type="flex" justify="space-between" align="middle">
            <span>学科名称</span>
            <el-input
              size="small"
              style="width: 50%"
              v-model="input"
              placeholder="请输入内容"
            ></el-input>
            <el-button size="small" @click="input = ''">清除</el-button>
            <el-button size="small" type="primary" @click="searchSubject"
              >搜索</el-button
            >
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-button
              size="small"
              icon="el-icon-edit"
              type="success"
              style="float: right"
              @click="addSubjects"
              >新增学科</el-button
            >
          </el-row>
        </el-col>
      </el-row>
      <!-- 提示文本 -->
      <el-alert style="margin: 15px 0" type="info" show-icon :closable="false"
        >数据一共{{ total }}条</el-alert
      >
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed type="index" label="序号"> </el-table-column>
        <el-table-column prop="subjectName" label="学科名称"> </el-table-column>
        <el-table-column prop="username" label="创建者"> </el-table-column>
        <el-table-column width="150px" prop="addDate" label="创建日期">
          {{ tableData.addDate | dateFormat("YYYY-MM-DD HH:mm:ss") }}
        </el-table-column>
        <el-table-column prop="isFrontDisplay" label="前台是否显示">
        </el-table-column>
        <el-table-column prop="twoLevelDirectory" label="二级目录">
        </el-table-column>
        <el-table-column prop="tags" label="标签"> </el-table-column>
        <el-table-column prop="totals" label="题目数量"> </el-table-column>
        <el-table-column label="操作" fixed="right" width="240px">
          <template slot-scope="{ row }">
            <el-row type="flex" justify="space-between" align="middle">
              <el-button
                type="text"
                @click="
                  $router.push(
                    `/subjects/directorys?id=${row.id}&name=${row.subjectName}`
                  )
                "
                >学科分类</el-button
              >
              <el-button
                type="text"
                @click="
                  $router.push(
                    `/subjects/tags?id=${row.id}&name=${row.subjectName}`
                  )
                "
                >学科标签</el-button
              >
              <el-button type="text" @click="addSubjects(row)">修改</el-button>
              <el-button type="text" @click="removeData(row)">删除</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页按钮-->
      <el-col>
        <el-row type="flex" justify="end">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pagesize"
            layout="prev, pager, next,sizes, jumper"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </el-col>
    </el-card>
    <!-- 新增学科弹出层 -->
    <el-dialog
      :title="title"
      :visible.sync="showDialog"
      width="50%"
      @close="btnCancel"
    >
      <el-form :model="formData" :rules="rules" ref="formData">
        <el-form-item prop="subjectName" label="学科名称">
          <el-input
            v-model="formData.subjectName"
            style="width: 80%"
            placeholder="请输入学科名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            v-model="formData.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            validate-event
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCancel">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { list, add, update, remove } from '@/api/hmmm/subjects'
export default {
  name: 'Subjects',
  data () {
    return {
      input: '',
      title: '新增学科',
      tableData: [],
      showDialog: false,
      pagesize: 10,
      currentPage: 1, // 当前活动页码
      total: 0, // 数据总条数
      formData: { //
        subjectName: '',
        isFrontDisplay: false// switch选择按钮
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
        // isFrontDisplay: [{ required: true }] // 前台是否显示,在后台无法观察,应该不是必须的参数,先不做校验
      }
    }
  },
  created () {
    this.getSubjectsList()
  },
  methods: {
    async getSubjectsList () { // 获取学科列表
      const { data: { counts, items } } = await list() // 获取了所有的数据记录
      // console.log(items)
      this.tableData = items // 拿到返回的列表数据,
      this.total = counts// 数据总条数存起来
    },
    async addSubjects (row) { // 新增学科 复用弹出层
      if (row.id) { // 新增是没有传递id的,修改才传递了id
        this.title = '修改学科'
        // 把当前行的数据,显示到输入框
        this.formData = { ...row, isFrontDisplay: !!row.isFrontDisplay }// id为1 转成true,0转为false
      } else {
        this.title = '新增学科'
      }
      this.showDialog = true
    },
    async submitData () {
    // 提交表单数据
      await this.$refs.formData.validate() // 校验表单数据
      if (this.title === '修改学科') {
        await update({ ...this.formData, isFrontDisplay: this.formData.isFrontDisplay ? 1 : 0 }) // 发送请求,提交数据
        this.$message.success('修改学科成功')
      } else {
        await add({ ...this.formData, isFrontDisplay: this.formData.isFrontDisplay ? 1 : 0 }) // 发送请求,提交数据
        this.$message.success('新增学科成功')
      }
      this.getSubjectsList()// 刷新列表
      this.formData = this.$options.data().formData // 重置数据
      this.showDialog = false // 关闭弹层
    },
    btnCancel () {
      // 取消的时候重置表单数据
      this.formData = this.$options.data().formData // 重置数据
      this.$refs.formData.resetFields() // 重置表单的校验数据
      this.showDialog = false // 关闭弹层
    },
    // 删除数据
    async removeData (row) {
      this.$confirm('确认删除这条数据吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        await remove(row)
        this.$message({
          message: '删除成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
        this.getSubjectsList()
      }).catch((error) => { console.log(error) })
    },
    async handleSizeChange (val) {
      this.currentPage = 1 // 先跳转到第一页,然后获取到数据刷新就是显示的第一页面
      // 切换 页容量 返回第一页
      const { data: { items } } = await list({ page: 1, pagesize: val }) // 拿到第一页的页码和切换的页容量去请求数据
      // 如果把分页跳转,写在这里,就会导致数据已经回来了,但是页面还没及时跳到第一页
      this.tableData = items // 刷新数据
      this.pagesize = val // 更新页容量
    },
    async handleCurrentChange (val) { // 切换页码,请求切换页的数据
      const { data: { items } } = await list({ page: val, pagesize: this.pagesize })// 拿到当前点击的页码 和默认的页容量去请求数据
      this.currentPage = val // 把当前活动页码,存起来
      this.tableData = items
    },
    async searchSubject () {
      this.currentPage = 1
      const { data: { items } } = await list({ page: 1, pagesize: this.pagesize, subjectName: this.input })
      this.total = items.length
      this.tableData = items
    }
  }
}
</script>

<style scoped lang='scss'>
.el-button + .el-button {
  margin-left: 0;
}
</style>
